declare global {
  interface Window {
    _AMapSecurityConfig: { securityJsCode: string };
  }
}

// 使用您提供的高德地图Key和安全密钥
const AMAP_KEY = '05779a3d55f04f0cb8c7bb581f19f46d';
const AMAP_SECURITY_CODE = '05779a3d55f04f0cb8c7bb581f19f46d';

export function MapLoader() {
  return new Promise((resolve, reject) => {
    // 设置安全配置（必需）
    window._AMapSecurityConfig = {
      securityJsCode: AMAP_SECURITY_CODE
    };

    // 检查是否已加载
    if (window.AMap) {
      resolve(window.AMap);
      return;
    }

    const callbackName = `initAMapCallback_${Date.now()}`;
    
    // 定义全局回调
    (window as any)[callbackName] = () => {
      if (window.AMap) {
        console.log('高德地图API加载成功');
        resolve(window.AMap);
      } else {
        console.error('高德地图API加载后未初始化');
        reject(new Error('高德地图API加载后未初始化'));
      }
      delete (window as any)[callbackName];
    };

    // 修复类型错误：使用更通用的类型定义
    const onError: OnErrorEventHandler = (event) => {
      console.error('高德地图API加载失败:', event);
      reject(new Error('高德地图API加载失败'));
      delete (window as any)[callbackName];
    };

const script = document.createElement('script');
script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.CircleMarker&callback=${callbackName}`;

// 直接定义 onerror 处理程序
script.onerror = (event: Event | string) => {
  // 处理两种可能的错误事件类型
  const errorEvent = typeof event === 'string' ? new Error(event) : event;
  console.error('高德地图API加载失败:', errorEvent);
  reject(new Error('高德地图API加载失败'));
  delete (window as any)[callbackName];
};

script.async = true;
    console.log('正在加载高德地图API...');
    document.head.appendChild(script);
  });
}

// 添加全局类型声明以解决类型问题
type OnErrorEventHandler = ((event: Event) => void) | null;